package me.toalec.RankUp.Permissions;

import java.util.ArrayList;
import java.util.LinkedHashSet;


import me.toalec.RankUp.util.Utility;

import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import com.nijiko.permissions.Entry;
import com.nijiko.permissions.Group;
import com.nijiko.permissions.PermissionHandler;
import com.nijiko.permissions.User;
import com.nijikokun.bukkit.Permissions.Permissions;

public class PermissionsYeti extends PermissionsBase{
	
	PermissionsYeti(Plugin instance){
		
		ph = ((Permissions)instance.getServer().getPluginManager().getPlugin("Permissions")).getHandler();
		Utility.printConsole("Permissions by Yeti initialized!");
	}

	@Override
	boolean hasPermission(Player player, String node) {
		return ph.has(player, node);
	}



	@Override
	boolean isValidPlayer(String playerName, Player worldReference) {
		return (ph.getUserObject(worldReference.getWorld().getName(), playerName) != null);
	}



	@Override
	boolean isValidGroup(String groupName, Player worldReference) {
		return (groupName != null && ph.getGroupObject(worldReference.getWorld().getName(), groupName) != null);
	}



	@Override
	ArrayList<String> getGroupName(String playerName, Player worldReference) {
		User user = ph.getUserObject(worldReference.getWorld().getName(), playerName);
		LinkedHashSet<Entry> group = user.getParents();
		ArrayList<String> str = new ArrayList<String>();
		for(Entry g: group)
			str.add(0, g.getName());
		return str;
	}



	@Override
	void removeGroup(String playerName, Player worldReference, String startingGroup) {
		User user = ph.getUserObject(worldReference.getWorld().getName(), playerName);
		Group firstGroup = ph.getGroupObject(worldReference.getWorld().getName(), startingGroup);
		user.removeParent(firstGroup);		
	}



	@Override
	void addGroup(String playerName, Player worldReference, String endingGroup) {
		User user = ph.getUserObject(worldReference.getWorld().getName(), playerName);
		Group firstGroup = ph.getGroupObject(worldReference.getWorld().getName(), endingGroup);
		user.addParent(firstGroup);
	}

	@Override
	void addPermission(Player player, String node) {
		ph.addUserPermission(player.getWorld().getName(), player.getName(), node);
	}
	
	private PermissionHandler ph;
}
